package com.okcl.security;

import cn.hutool.json.JSONUtil;
import com.okcl.dto.Result;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.stereotype.Component;

import java.io.IOException;

/**
 * 匿名访问私有化资源时的处理器
 */
@Component
public class LoginUnAuthenticationEntryPointHandler implements AuthenticationEntryPoint {

    /**
     * 认证失败处理
     *
     * @param request
     * @param response
     * @param authException
     * @throws IOException
     */
    @Override
    public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException authException) throws IOException, ServletException {
        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/json");
        Result error = Result.error("认证失败");
        String jsonStr = JSONUtil.toJsonStr(error);
        response.getWriter().println(jsonStr);
    }
}
